import router from "../index";
import { useLayoutStore } from "@/stores/layout";

// 根据后端返回内容, 生成路由
export const generateRoutes = (routes) => {
	const modules = import.meta.glob("../../views/**/*.vue");

	// 递归函数
	const deleKeyArr = ["path", "name", "component", "redirect", "children", "redirect"];
	function recursionRoutes(re_routes) {
		re_routes.forEach((routeItem) => {
			// 菜单
			if (routeItem.type === "menu") {
				routeItem.component = modules[`../../views${routeItem.component}.vue`];
			}
			// 目录_为它设置组件后,即可开启多级路由
			if (routeItem.type === "catalogue" && routeItem.component) {
				routeItem.component = modules[`../../views${routeItem.component}.vue`];
			}

			routeItem.meta = JSON.parse(JSON.stringify(routeItem));
			deleKeyArr.forEach((key) => delete routeItem.meta[key]);

			if (routeItem.children) recursionRoutes(routeItem.children);
		});
	}

	recursionRoutes(routes);
	routes.forEach((routeItem) => router.addRoute("Layout", routeItem));

	// 进入首页
	router.push("/");
	useLayoutStore().addTags({ index: "/home" });
};
